<?php

/**
 * @category   Ac
 * @package    Ad
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     Olivier Bregeras
 */
class Listing_IndexController extends Ac_Controller_Action {

    public function indexAction() {
        // action body
    }

    public function displayAction() {
    	
        //$this->_helper->_layout->setLayout('ad-details-layout2');
        /*
		$patterns = new Zend_Config_Ini(APPLICATION_PATH.'/configs/face.ini','face');
		$patterns = $patterns->face->toArray();
		$replacements = new Zend_Config_Ini(APPLICATION_PATH.'/configs/face.ini','sign');
		$replacements = $replacements->sign->toArray();
		print_r($patterns);print_r($replacements);
		die();
		*/
        $params = $this->_request->getParams();
        
		Model_Visit::visit(new MongoId($params['id']));
        //Model_Listing_Preview::translateAnAd($params['id']);
        // echo Model_Listing::all(array('sa' => 1, 'at' => array('$exists'=>0)))->count();
        // exit;

        $listing = Model_Listing::find(new MongoId($params['id']));
		$this->view->listing_id = $params['id'];
        if ($listing == null) {// listing not found
            throw new Ac_Exception_MissingListing('not found');
        }

        if (empty($this->loggedin_user) && (int)$listing->status !== (int)Model_Listing::STATUS_PUBLISHED) {
            throw new Ac_Exception_MissingListing('draft - user not logged in');
        }

        if (!empty($this->loggedin_user) &&
                ((int)$listing->status !== (int)Model_Listing::STATUS_PUBLISHED &&
                (string) $listing->user->_id !== (string) $this->loggedin_user->_id
                )
        ) {
            throw new Ac_Exception_MissingListing('draft - not belonging to user');
        }

        //be sure that the title provided is the right one
        //var_dump(urldecode(trim($params['title'])), urldecode(trim($listing->title_url)), $listing->url());exit;
        if (preg_replace('#\v#', '', urldecode(trim($params['title']))) != preg_replace('#\v#', '', trim(urldecode($listing->title_url)))) {
            $this->_redirect($listing->url(), array('code' => 301));
            //var_dump($listing->title_url, $listing);exit;
        }

        Model_History::addListing($listing->_id);
        $to_add = '';
        if ((string) $listing->category[0]->path[0] == '4cda3e818835c16810770100') { //mc56 Pets
            $to_add = $listing->category[0]->name . ' - ';
        }
        //add header for facebook
        $this->view->headMeta()->appendName('og:type', 'product');
        if (!empty($listing->title)) {
            /*
            $internal_lng = $listing->getInternalLanguage();
            if ($listing->at == Model_Listing::ORIGINAL_LANGUAGE_EN && $this->current_language == 'en' && $internal_lng == 'tc') {
                $this->view->headMeta()->appendName('og:title', $to_add . ' - ' . $listing->title_en);
                $this->addTitle($to_add . $listing->title_en);
            } elseif ($listing->at == Model_Listing::ORIGINAL_LANGUAGE_EN  && $internal_lng == 'tc') {
                $this->view->headMeta()->appendName('og:title', $to_add . ' - ' . $listing->title_en);
                $this->addTitle($to_add . $listing->title_en);
            } else {
                $this->view->headMeta()->appendName('og:title', $to_add . ' - ' . $listing->title);
                $this->addTitle($to_add . $listing->title);
            }
            */
            if (!empty($listing->area_l2)) {
                $this->view->headMeta()->appendName('og:title', $listing->area_l2->area_l1->name . $listing->area_l2->name . $listing->category[0]->name);
                $this->addTitle($listing->area_l2->area_l1->name . $listing->area_l2->name . $listing->category[0]->name);            
            }
            $this->view->headMeta()->appendName('og:title', $listing->title);
            $this->addTitle($listing->title);
            

        }
        if (!empty($listing->description)) {
            $this->view->headMeta()->appendName('og:description', substr($listing->description, 0, 100));
            $this->view->headMeta()->appendName('description', substr($listing->description, 0, 100));
        }
        $this->view->headMeta()->appendName('keywords', $to_add . implode(', ', $listing->getKeyword()));
        $this->view->headMeta()->appendName('og:url', $listing->url(true));

        if (!empty($listing->longitude)) {
            $this->view->headMeta()->appendName('og:longitude', $listing->longitude);
        }
        if (!empty($listing->latitude)) {
            $this->view->headMeta()->appendName('og:latitude', $listing->latitude);
        }
        if (!empty($listing->photos[0])) {
            $this->view->headMeta()->appendName('og:image', $this->view->thumbnail()->resizeAndCrop($listing->photos[0], 130, 110));
        }

        //$this->_title[] = $listing->title;
        $this->setCanonical($listing->url());

        $config = array('listing' => $listing);
        if (!empty($this->loggedin_user->_id)) {
            $config['user'] = $this->loggedin_user;
        }

        if (!empty($listing->category[0]) && !empty($listing->category[0]->path[0])) {
            if ($listing->category[0]->customization == 'job') {
                $config['allow_upload'] = true;
            }
            Zend_Registry::set('main_category', Model_Category::find($listing->category[0]->path[0]));
        }

        if (!$listing->sold) {
            $form = new Listing_Form_SendMessageForm($config);

            if ($this->_request->isPost() && $form->isValid($_POST)) {
                //if ($this->_request->isPost()) {
                //save email send to
                $session = new Zend_Session_Namespace('send_message');
                $tmp = array();
                $tmp[(string) $listing->_id] = $_POST['email'];
                $session->listing = $tmp;
                $form->save();
                $this->_redirect($this->view->geturl('send-message', 'listing', null, null, array('id' => (string) $listing->_id)));
            } elseif ($this->_request->isPost()) {
                //var_dump($form->getErrors());
            }
            $this->view->send_message_form = $form;
        }

		$this->view->similar_ads_user = $listing->findRelated(4, Model_Listing::RELATED_SAME_USER);
		//$this->view->similar_ads_user2 = $listing->findRelated(4, Model_Listing::RELATED_SAME_TITLE + Model_Listing::RELATED_SAME_USER);
		if (empty($this->view->similar_ads_user)) {
			$this->view->similar_ads_user = $listing->findRelated(4, Model_Listing::RELATED_SAME_USER);
		}
		if (empty($this->view->similar_ads_user)) {
			$related_others = 8;
		} else {
			$related_others = 4;
		}

		//$this->view->similar_ads_other = $listing->findRelated($related_others, Model_Listing::RELATED_SAME_TITLE | Model_Listing::RELATED_EXCLUDE_SAME_USER);

		//if ($this->view->similar_ads_other->count() == 0) {
			$this->view->similar_ads_other = $listing->findRelated($related_others, Model_Listing::RELATED_SAME_CATEGORY | Model_Listing::RELATED_EXCLUDE_SAME_USER);
		//}

        if ($this->view->similar_ads_other->count() == 0) {
            $this->view->similar_ads_other = $listing->findRelated($related_others, Model_Listing::RELATED_TOP_CATEGORY | Model_Listing::RELATED_EXCLUDE_SAME_USER);
        }


        if ($listing->sold || ($listing->user && $listing->user->no_send_message)) {
            $this->view->similar_ads_user = $listing->findRelated(3, Model_Listing::RELATED_SAME_TITLE + Model_Listing::RELATED_SAME_USER);
            if (empty($this->view->similar_ads_user_sold)) {
                $this->view->similar_ads_user_sold = $listing->findRelated(3, Model_Listing::RELATED_SAME_USER);
            }
            $this->view->similar_ads_other_sold = $listing->findRelated(6, Model_Listing::RELATED_SAME_TITLE | Model_Listing::RELATED_EXCLUDE_SAME_USER);
            if (empty($this->view->similar_ads_other_sold)) {
                $this->view->similar_ads_other = $listing->findRelated(6, Model_Listing::RELATED_SAME_CATEGORY | Model_Listing::RELATED_EXCLUDE_SAME_USER);
            }
        }
             
        if (!empty($_GET['sid'])) {
//            $this->view->search = Model_Search::find($_GET['sid']);
        }

        //load bookmark
        
        $list = Model_Bookmark::getList();
        $bookmark = array();
        if (!empty($list)) {
            foreach ($list as $bmk) {
                if (!empty($bmk->listing)) {
                    $bookmark[] = (string) $bmk->listing->_id;
                }
            }
        }
        $this->view->bookmark = $bookmark;
         

        //find procuts also liked


        //find latest products from the same top category
        $this->view->list_latest_cat = $listing->getLatestListing();



        $listing->newView();

        $this->view->listing = $listing;
        //$this->render('display-job');
        $allface = new Zend_Config_Ini(APPLICATION_PATH.'/configs/face.ini','face');
		$allface = $allface->face->toArray();
		$this->view->allface = $allface;
		$allsign = new Zend_Config_Ini(APPLICATION_PATH.'/configs/face.ini','sign');
		$allsign = $allsign->sign->toArray();
		$this->view->allsign = $allsign;
		
        $this->view->history_comments = Model_Comment::fetchAll(array('list_id'=>$params['id'], 'status'=>array('$in'=>array('new', 'suspicious', 'edited', 'reactivated'))));
        
        $comment_form = new Listing_Form_AddNewCommentForm();
        $this->view->comment = $comment_form;
    }

    public function sendMessageAction() {
        $listing = Model_Listing::find(new MongoId($_GET['id']));

        if (empty($listing)) {
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect('/');
        }
        $this->view->listing = $listing;
        $session = new Zend_Session_Namespace('send_message');
        $this->view->email = $session->listing[$_GET['id']];

        $temp = array();
        $similar_title = $listing->findRelated(10, Model_Listing::RELATED_SAME_TITLE);
        if (count($similar_title) < 10) {
            foreach($similar_title as $s_t){
				$temp[] = $s_t;
			}//echo "1 ".count($temp)."<br>";
            $similar_cat = $listing->findRelated(10, Model_Listing::RELATED_SAME_CATEGORY);
            foreach($similar_cat as $s_c){
				$temp[] = $s_c;
				if(count($temp)==10){
					break;
				}
			}
            //echo "2 ".count($temp)."<br>";
            if (count($temp) < 10) {
	            $similar_top = $listing->findRelated(10, Model_Listing::RELATED_TOP_CATEGORY);
	            foreach($similar_top as $s_to){
					$temp[] = $s_to;
					if(count($temp)==10){
						break;
					}
				}
				//echo "3 ".count($temp)."<br>";
	        }
        }else{
			$temp = $similar_title;
		}
		$this->view->similar_ads = (object)$temp;
    }
    
    public function postingSuccessAction(){
    	if(empty($_GET['new']) || empty($this->loggedin_user)){
			$this->_redirect('/');
		}
		$this->_helper->_layout->setLayout('post-layout');
		$this->view->listing = Model_Listing::find(new MongoId($_GET['new']));
		$listing = Model_Listing::find(new MongoId($_GET['new']));
		$this->view->similar_ads_other = $listing->findRelated(10, Model_Listing::RELATED_SAME_TITLE | Model_Listing::RELATED_EXCLUDE_SAME_USER);

		if ($this->view->similar_ads_other->count() == 0) {
			$this->view->similar_ads_other = $listing->findRelated(10, Model_Listing::RELATED_SAME_CATEGORY | Model_Listing::RELATED_EXCLUDE_SAME_USER);
		}

        if ($this->view->similar_ads_other->count() == 0) {
            $this->view->similar_ads_other = $listing->findRelated(10, Model_Listing::RELATED_TOP_CATEGORY | Model_Listing::RELATED_EXCLUDE_SAME_USER);
        }
		$this->render('post-an-ad-success-page');
	}

    public function validateSendMessageAction() {
        $form = new Listing_Form_SendMessageForm();
        unset($_POST['captcha']);
        $form->isValidPartial($_POST);
        $this->_helper->json($form->getMessages());
    }

    public function previewAction() {
        if (empty($_POST['category'])) {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing', null, null, array('error' => 1)));
        }

        $this->_helper->_layout->setLayout('login-layout');
        $session = new Zend_Session_Namespace('post-an-ad');

        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }
        //var_dump($_GET, $_SESSION);exit;
        $session = new Zend_Session_Namespace('post-an-ad');
        //$session->unsetAll();
        //var_dump($_POST, $_SESSION);exit;


        if (!empty($_POST['adid'])) {
            $u = Model_Listing_Preview::find($_POST['adid']);
            if (empty($u)) {
                $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
            }
        } else {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
        }


        $category = array();
        foreach ((array) $_POST['category'] as $cat_id) {
            if (!empty($cat_id)) {
                $u->addCategory($cat_id);
            }
        }

        $options = array();
        $options['adid'] = (string) $u->_id;
        $options['listing'] = $u;
        $form = $u->postAnAddForm($options);

        $form->populate((array) $_POST);
        $listing = $form->save(true); //preview mode

        $this->view->mode = 'preview';
        $this->view->listing = $listing;
        //$this->render('display');
    }

    public function editAction() {
        //$session = new Zend_Session_Namespace('post-an-ad');
        //$session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        //$ad = Model_Listing_Preview::convertFromListing($ad);
        //$ad->save();
        //$ad->photos_tmp = $ad->photos;
        if ($ad instanceof Model_Listing_Regular) {
            $session = new Zend_Session_Namespace('post-an-ad');
            $session->listing_started = $_GET['id'];
        }

        foreach ($ad->category as $cat) {
            $_GET['category'][] = (string) $cat->_id;
        }
        return $this->_forward('post-an-add-information');
    }

    public function editTranslationAction() {

        $ad = Model_Listing::find($_GET['id']);

        if ($ad instanceof Model_Listing_Regular) {
            $session = new Zend_Session_Namespace('post-an-ad');
            $session->listing_started = $_GET['id'];
        }

        foreach ($ad->category as $cat) {
            $_GET['category'][] = (string) $cat->_id;
        }
        return $this->_forward('post-an-add-information');
    }

    public function translateAction() {

        $this->_helper->_layout->setLayout('login-layout3');
        $session = new Zend_Session_Namespace('post-an-ad');

        $ad = Model_Listing::find($_GET['id']);
        foreach ($ad->category as $cat) {
            $_GET['category'][] = (string) $cat->_id;
        }
        $classname = Model_Listing::getInstanceClassname((array) $_GET['category']);
        $u = Model_Listing::getInstance($classname, $ad->_id);
        $u = Model_Listing_Preview::convertFromListing($u);

        $category = array();
        if (!empty($_GET['category'])) {
            $u->ca = array();
            foreach ((array) $_GET['category'] as $cat_id) {
                if (!empty($cat_id)) {
                    $u->addCategory($cat_id);
                }
            }
        }

        
		$options                 = array();
        $options['adid']         = (string) $u->_id;
        $options['listing']      = $u;
		$options['category']      = $_GET['category'];
		// print_r($u);
		// exit;
		
		
	    $form = new Listing_Form_PostAnAddTranslateForm($options);
        $form->populate((array)$_POST);
		
		if($this->_request->isPost() && isset($_POST['back'])){
			$ad = $form->save();
			
			$_POST = array();
			$session->unsetAll();
			$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
			$to_be_confirmed_ads->unsetAll();
			$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
			$to_be_confirmed_ads->setExpirationSeconds(10000000);
			$arr = (array)$to_be_confirmed_ads->arr;
			$arr[] = $ad->_id;
			$to_be_confirmed_ads->arr = $arr;
			$to_be_confirmed_ads->lock();
			if (!empty($_GET['mode']))
			$this->_redirect($this->view->geturl('edit-translation', 'listing', null, null, array('id'=> (string) $u->_id, 'mode' => 1)));
			else
			$this->_redirect($this->view->geturl('edit-translation', 'listing', null, null, array('id'=> (string) $u->_id, 'type' => 'new')));
		}
		
		if (isset($_POST['continue'])) { 
			$ad = $form->save();
			
			$_POST = array();
			$session->unsetAll();
			$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
			$to_be_confirmed_ads->unsetAll();
			if (Zend_Registry::isRegistered('loggedin_user')) {
			   
				if (empty($_GET['type'])) {
						if ($this->loggedin_user->role == Model_User::ROLE_ADMIN && (string) $ad->user->_id != (string) $this->loggedin_user->_id) {
							$this->_redirect($ad->url());
						} else {
							$this->_redirect($this->view->geturl('my-account-ads', 'user'));
						}
					} else {
					$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
					$to_be_confirmed_ads->setExpirationSeconds(10000000);
					$arr = (array)$to_be_confirmed_ads->arr;
					$arr[] = $ad->_id;
					$to_be_confirmed_ads->arr = $arr;
					$to_be_confirmed_ads->lock();
					$this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('loggedin' => 1, 'return'=> (string) $ad->_id, 'login_process' => 1)));
				}
			} else {
				
				$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
				$to_be_confirmed_ads->setExpirationSeconds(10000000);
				$arr = (array)$to_be_confirmed_ads->arr;
				$arr[] = $ad->_id;
				$to_be_confirmed_ads->arr = $arr;
				$to_be_confirmed_ads->lock();
				$this->_redirect($this->view->geturl('login', 'user', null, null, array('return'=> (string) $ad->_id)));
			}
		}
	 
		
		$this->view->category = $u->getCategory();
		$this->view->form = $form;
	
	}
	
        public function postAnAddInformationAction() {

        /*
          if ($this->_request->isGet()) {
          $this->_redirect($this->view->geturl('post-an-ad','listing'));
          } */

        if (empty($_GET['category'])) {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing', null, null, array('error' => 1)));
        }


        $this->_helper->_layout->setLayout('login-layout');
        $session = new Zend_Session_Namespace('post-an-ad');

        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }

        //var_dump($_GET, $_SESSION);exit;
        $session = new Zend_Session_Namespace('post-an-ad');
        //$session->unsetAll();
        //Edit
        if (!empty($_GET['id']) && $this->_request->isGet()) {
            $classname = Model_Listing::getInstanceClassname((array) $_GET['category']);
            $u = Model_Listing::getInstance($classname, $_GET['id']);
            $u = Model_Listing_Preview::convertFromListing($u);
        } elseif (!empty($_GET['id']) && $this->_request->isPost()) {
            $classname = Model_Listing::getInstanceClassname((array) $_POST['category']);
            $u = Model_Listing_Preview::getInstance($classname, $_GET['id']);

            //echo '<pre>';print_r($u);exit;
        } else if (!empty($session->listing_started)) {	
            $classname = Model_Listing::getInstanceClassname((array) $_GET['category']);		
            $u = Model_Listing_Preview::getInstance($classname, $session->listing_started);
            if (empty($u)) {
                $u = Model_Listing::getInstance($classname, $session->listing_started);
            }
        } else {
            $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
        }

        //var_dump($session->listing_started, (string) $u->_id);
        $category = array();
        if (!empty($_GET['category'])) {
            $u->ca = array();
            foreach ((array) $_GET['category'] as $cat_id) {
                if (!empty($cat_id)) {
                    $u->addCategory($cat_id);
                }
            }
        }

        //if default photo uploader used

        if ($this->_request->isPost() && !empty($_FILES)) {
            //echo "<pre>";print_r($_FILES);echo "</pre>";exit;
            /* if (($_FILES['upload1']['error'] != 4) && 
              ($_FILES['upload2']['error'] != 4) ||
              ($_FILES['upload3']['error'] != 4) ||
              ($_FILES['upload4']['error'] != 4)) { */
            if ($_FILES['upload1']['error'] != 4) {

                //move_uploaded_file($_FILES['upload1']['tmp_name'], '/tmp/test.jpg');
                //var_dump($_FILES, is_uploaded_file($_FILES['upload1']['tmp_name']));exit;
                $_SERVER['HTTP_ADID'] = $u;
                $_SERVER['NOT_JSON'] = 1;
                $res = Ac_Util::uploadListingPhotoProcess();
                //echo "<pre>";var_dump($res);echo "</pre>";exit;
            }
        }

        $options = array();
        $options['preview_link'] = $this->view->geturl('preview', 'listing');
        $options['adid'] = (string) $u->_id;
        $options['listing'] = $u;
        $form = $u->postAnAddForm($options);

        $form->populate((array) $_POST);
        /*
          var_dump($this->_request->isPost(),
          $form->isValid($_POST),
          !empty($this->loggedin_user), $this->loggedin_user->role == Model_User::ROLE_ADMIN, ($this->_request->isPost() &&
          ($form->isValid($_POST) ||
          (!empty($this->loggedin_user) && $this->loggedin_user->role == Model_User::ROLE_ADMIN))));exit;
         * 
         */

        if ($this->_request->isPost() &&
                ($form->isValid($_POST) ||
                (!empty($this->loggedin_user) && $this->loggedin_user->role == Model_User::ROLE_ADMIN))) {
            if (isset($_POST['postyourad'])) {
                $ad = $form->save();

                $_POST = array();
                $session->unsetAll();
                $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                $to_be_confirmed_ads->unsetAll();
                if (Zend_Registry::isRegistered('loggedin_user')) {
                    //$this->_redirect($ad->url());

                    if (empty($_GET['type'])) {
                        /*if ($this->loggedin_user->role == Model_User::ROLE_ADMIN && (string) $ad->user->_id != (string) $this->loggedin_user->_id) {
                            $this->_redirect($ad->url());
                        } else {
                            $this->_redirect($this->view->geturl('my-account-ads', 'user'));
                        }*/
                        $this->_redirect($this->view->geturl('posting-success', 'listing', null, null, array('new' => (string) $ad->_id)));
                    } else {
                        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                        $to_be_confirmed_ads->setExpirationSeconds(10000000);
                        $arr = (array) $to_be_confirmed_ads->arr;
                        $arr[] = $ad->_id;
                        $to_be_confirmed_ads->arr = $arr;
                        $to_be_confirmed_ads->lock();
                        $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('loggedin' => 1, 'return' => (string) $ad->_id, 'login_process' => 1)));
                    }
                } else {
                    //redirect to register the user
                    //save $ad id as a cookie or permanent session

                    $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                    $to_be_confirmed_ads->setExpirationSeconds(10000000);
                    $arr = (array) $to_be_confirmed_ads->arr;
                    $arr[] = $ad->_id;
                    $to_be_confirmed_ads->arr = $arr;
                    $to_be_confirmed_ads->lock();
                    //echo '<pre>';print_r($_SESSION);exit;
                    $this->_redirect($this->view->geturl('login', 'user', null, null, array('return' => (string) $ad->_id)));
                }
            }

            if (isset($_POST['review'])) {
                $ad = $form->save();

                $_POST = array();
                $session->unsetAll();

                $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
                $to_be_confirmed_ads->setExpirationSeconds(10000000);
                $arr = (array) $to_be_confirmed_ads->arr;
                $arr[] = $ad->_id;
                $to_be_confirmed_ads->arr = $arr;
                $to_be_confirmed_ads->lock();
                if (!isset($_GET['validate']))
                    $this->_redirect($this->view->geturl('translate', 'listing', null, null, array('id' => (string) $ad->_id, 'mode' => 1)));
                else
                    $this->_redirect($this->view->geturl('translate', 'listing', null, null, array('id' => (string) $ad->_id, 'type' => 'new')));
            }
        }


        $this->view->category = $u->getCategory();
        $this->view->form = $form;
        $this->view->url_en = $this->url_en();
        $this->view->url_tc = $this->url_tc();
        $this->render('post-an-ad-info');
    }

    public function postAnAdAction() {
        //for biz accounts, redirect to biz info form
        if (!empty($this->loggedin_user)) {
            $temp = Zend_Registry::get('loggedin_user');
            $session_url = new Zend_Session_Namespace('return _url');
            if ($temp->type_account & Model_User::COMPANY_ADMIN) {
                $company = $temp->company;

                if (empty($company->cn) || empty($company->bc)) {
                    //echo "<pre>";var_dump($company);echo "</pre>";exit();
                    $session_url->listing = $this->view->geturl('post-an-ad', 'listing');
                    $this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('post-an-ad-inc' => '1')));
                }
            }
        }

        $session = new Zend_Session_Namespace('post-an-ad');
        if (!empty($_GET['change']) && !empty($session->listing_started)) {
            $ad = Model_Listing_Preview::one(array('_id' => new MongoId($sessionc)));
            if (empty($ad)) {
                $ad = new Model_Listing_Preview();
                $ad->status = Model_Listing::STATUS_STARTED;
                $ad->save();
            }
        } else {
            $ad = new Model_Listing_Preview();
            $ad->status = Model_Listing::STATUS_STARTED;
            $ad->save();
        }

        if (!empty($_GET['category'])) {
            $tmp = array();
            foreach ((array) $_GET['category'] as $cat) {
                $tmp[] = Model_Category::find($cat);
            }
            $this->view->selected_category = $tmp;
        }

        $session->setExpirationSeconds(10 * 365 * 24 * 3600); //10 years
        $session->listing_started = (string) $ad->_id;
        $this->_helper->_layout->setLayout('login-layout');

        if (empty($session->current_post)) {
            $session->current_post = new StdClass();
        }
        if (!empty($_GET['change'])) {
            $this->view->listing = $ad;
        }

        $this->view->level1 = Model_Category::getLevel1(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array('pos' => 1));
        $this->view->level2 = Model_Category::getLevel2(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array('path.0' => 1, 'pos' => 1));
        $this->view->level3 = Model_Category::getLevel3(array('post_an_ad' => 1, 'status' => Model_Category::STATUS_ACTIVE))->sort(array('path.1' => 1, 'pos' => 1));
        $this->render('post-an-ad-category');
    }

    public function geocodeAction() {
        if ($this->_request->isPost()) {
            $listing = Model_Listing_Preview::find($_POST['id']);
            $preview = true;
            if (empty($listing)) {
                $listing = Model_Listing::find($_POST['id']);
                $preview = false;
            }

            if (empty($listing->latitude)) {
                $listing->latitude = $_POST['latitude'];
            }
            if (empty($listing->longitude)) {
                $listing->longitude = $_POST['longitude'];
            }
            if (empty($listing->area_l2)) {
                $preview = false;
            } else {
                if ($res = Model_Location::one(array('nm_en' => $listing->area_l2))) {                    
                    $preview = true;
                } elseif ($res = Model_Location::one(array('nm_tc' => $listing->area_l2))) {                    
                    $preview = true;
                } else {
                    $preview = false;
                }
            }
            
            if(empty($this->area_l2) && !empty($_POST['area_l2'])) {
                $id = '';
                if ($item = Model_Location::one(array('nm_en' => $_POST['area_l2']))) {                    
                    $id = $item->_id;
                } elseif ($item = Model_Location::one(array('nm_tc' => $_POST['area_l2']))) {                    
                    $id = $item->_id;
                } elseif (strtolower($_POST['area_l2']) == 'mid-level') {
                    $id = '4cbe455a8835c17c10130000';//midlevels
                } elseif(strtolower($_POST['area_l2']) == 'tai hang') {
                    $id = '4cbe455a8835c17c100b0000'; //causeway bay
                } else {
                    file_put_contents('/tmp/missing_location_geocode', $_POST['area_l2']."\n", FILE_APPEND);
                }
	
                if (empty($item)) {
                    $item = Model_Location::find(new MongoId($id));
                }
                if(!empty($item)) {
                    $listing->area_l2 = new MongoId($id);
                }
            }
            
            if (!$preview) {
                $listing->forceSave();
            }
        }
        exit;
    }

    public function deletePhotoAction() {
        //$listing = Model_Listing::find($_POST['adid']);
        $listing = Model_Listing_Preview::find(new MongoId($_POST['adid']));
        if (empty($listing)) {
            $listing = Model_Listing::find(new MongoId($_POST['adid']));
        }
        if (!empty($listing->user->_id) && (string) $this->loggedin_user->_id != (string) $listing->user->_id) {
            $res = 'nok';
            $this->_helper->json(array('res' => $res));
        }
        $photos = $listing->photos;
        unset($photos[$_POST['num']]);
        $photos = array_values($photos);
        $listing->photos = $photos;
        if (!empty($listing->photos_tmp)) {
            $photos = $listing->photos_tmp;
            unset($photos[$_POST['num']]);
            $photos = array_values($photos);
            $listing->photos_tmp = $photos;
        }
        $listing->save();
        $res = 'ok';
        $this->_helper->json(array('res' => $res));
    }

    public function featurePhotoAction() {
        //$listing = Model_Listing::find($_POST['adid']);
        $listing = Model_Listing_Preview::find(new MongoId($_POST['adid']));
        if (empty($listing)) {
            $listing = Model_Listing::find(new MongoId($_POST['adid']));
        }
        if (!empty($listing->user->_id) && (string) $this->loggedin_user->_id != (string) $listing->user->_id) {
            $res = 'nok';
            $this->_helper->json(array('res' => $res));
        }
        $photos = $listing->photos;
        //unset($photos[$_POST['num']]);
        $listing->featured_photo_id = (int) $_POST['id'];
        $photos = array_values($photos);
        $listing->photos = $photos;
        $listing->save();
        $res = 'ok';
        $this->_helper->json(array('res' => $res));
    }

    public function publishAction() {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }
        $ad->publish();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) {
            $tab = $_GET['tab'];
        } else {
            $tab = 1;
        }
        $this->_redirect('/user/my-account-ads?ac=publish&nb=1&tab=' . $tab);
    }

    public function unpublishAction() {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->unpublish();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) {
            $tab = $_GET['tab'];
        } else {
            $tab = 1;
        }
        $this->_redirect('/user/my-account-ads?ac=unpublish&nb=1&tab=' . $tab);
    }

    public function renewAction() {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->renew();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) {
            $tab = $_GET['tab'];
        } else {
            $tab = 1;
        }
        $this->_redirect('/user/my-account-ads?ac=renew&nb=1&tab=' . $tab);
    }

    public function deleteAction() {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->deleteListing();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) {
            $tab = $_GET['tab'];
        } else {
            $tab = 1;
        }
        $this->_redirect('/user/my-account-ads?ac=delete&nb=1&tab=' . $tab);
    }

	public function deleteAdAction() {
        $session = new Zend_Session_Namespace('post-an-ad');
        $session->listing_started = $_GET['id'];
        $ad = Model_Listing::find($_GET['id']);
        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->deleteListing();
        //$this->_redirect($this->view->geturl('my-account-ads', 'user'));
        if (isset($_GET['tab'])) {
            $tab = $_GET['tab'];
        } else {
            $tab = 1;
        }
        $this->_redirect('/user/my-account?del=1');
    }

    public function markAsSoldAction() {
        $ad = Model_Listing::find($_GET['id']);

        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->markAsSold();
        $this->_redirect($this->view->geturl('my-account-ads', 'user'));
    }

    public function markAsUnSoldAction() {
        $ad = Model_Listing::find($_GET['id']);

        if (empty($this->loggedin_user) || empty($ad->user->_id) || (string) $this->loggedin_user->_id != (string) $ad->user->_id) {
            $this->_redirect($this->view->geturl('my-account-ads', 'user', null, null, array('error' => 'not-allowed')));
        }

        $ad->markAsUnSold();
        $this->_redirect($this->view->geturl('my-account-ads', 'user'));
    }

    public function translatorAction() {
        $c = $_GET['c'];
        if (Zend_Registry::get('current_language') == 'en') {
            $ft = 'en';
            $tt = 'zh-TW';
        } else {
            $ft = 'zh-TW';
            $tt = 'en';
        }
        $value = Ac_Translation::execute($c, $tt, $ft);
        $view = $this->view;
        if (!empty($value)) {
            $this->_helper->json($value);
        } else {
            $this->_helper->json('');
        }
    }
	
    public function addnewcommentAction() {
    	if($this->_request->isPost() && $this->_request->isXmlHttpRequest()){
    		$arr = array();
    		$post_new_comment = $this->_request->getPost();
    		$form = new Listing_Form_AddNewCommentForm();
    		
    		if($form -> isValid($this->_request->getPost())){
    			$new_comment_content = $post_new_comment['add_comments'];
    			
    			$new_comment_content = str_replace("\r\n","<br />",strip_tags($new_comment_content));
    			$new_comment_content = $new_comment_content;
    			try{
	    			$new_comment = new Model_Comment();
	    			$new_comment -> list_id = $post_new_comment['id'];
	    			$new_comment -> content = $new_comment_content;
	    			$new_comment -> user_id = $this->loggedin_user->_id;
	    			if(Model_Util::againstBannedWords($new_comment_content) === true)
	    			{
	    				$new_comment -> status = 'new';
	    			}
	    			else{
	    				$new_comment -> status = 'suspicious';
	    			}
	    			$new_comment -> created_at = new MongoDate();
	    			if($new_comment -> save()){  			
	    				$arr['status'] = 'success';
	    				if($new_comment -> status === 'new')
	    				{
	    					$arr['content'] = Model_Comment::addface($new_comment_content);
	    				}
	    				else{
	    					$arr['content'] = "Your comment will be reviewed by our moderators. Thank you.";
	    				}
	    				$arr['created_at'] = date ('Y-m-d H:i', $new_comment -> created_at->sec);
	    				$arr['user_name'] = Model_User::find(new MongoId($this->loggedin_user->_id))->username;
	    				$arr['pic'] = $this->view->thumbnail()->scale(Model_User::find(new MongoId($this->loggedin_user->_id))->profile_picture, 54, 54, true, true);
	    				$arr['url'] = Model_User::find(new MongoId($this->loggedin_user->_id))->url();
	    			}
    			}	catch (Ac_User_Behavior_Exception $e) {
    				$arr['status'] = $e->getMessage;
		        }
    		}else{
    			$arr['status'] = $form->getMessages();
    		}
    		$this->_helper->json($arr);
    	}else {
    		$this->_redirect('/');
    	}
    }
    
    
    public function addnewcomplainAction(){
    	if($this->_request->isPost() && $this->_request->isXmlHttpRequest()){
    		$arr = array();
    		$post_new_complain = $this->_request->getPost();
    		$form = new Listing_Form_AddNewComplainForm();
    		
    		if($form -> isValid($this->_request->getPost())){
	    		try {
	    			$arr_id = explode('_',$post_new_complain['id']);
	    			$new_complain = new Model_Complain();
	    			$new_complain -> complain_content = $post_new_complain['n'];
	    			$new_complain -> comment_id = new MongoId($arr_id[1]);
	    			$new_complain -> user_id = Model_Comment::find(new MongoId($arr_id[1]))->user_id;
	    			$new_complain -> created_at = time();
	    			if($new_complain->save()){
	    				$arr['status'] = 'success';
	    			}
	    		}catch (Ac_User_Behavior_Exception $e) {
	    			$arr['status'] = $e->getMessage;
	    		}
    		}else{
    			$arr['status'] = $form->getMessages();
    		}
    		$this->_helper->json($arr);
    	}else{
    		$this->_redirect('/');
    	}
    }  
    
    
	public function addanadlocalAction() 
	{
//		$a2c = new Model_A2c();
//		$a2c->postUserSignup('a2ctest_dev_vvxxkkgg', 'a2ctest_dev_vvxxkkgg@mail.com', '123456', '123456789', 0);
		
//		$a2c->postUserLogin('a2ctest_dev_vvxxkkgg@mail.com', '123456');

//		$a2c->getTopCategory();

//		$a2c->getSpecificCategory('4cda3e818835c16810000000');
		
//		$a2c->postListing(
//			'sc', 'title', 'description', 
//			$category = array('4edf1ddfe62d6ca57664b090'), 
//			$userid = '4fbc53867f8a7ea947001bde', 
//			$sessionid = '1338193681-4fc337116e2fd8.34338305', 
//			$district = ENTIRE_CITY, 
//			$photos = array('path/photo1_test_justpost', 'path/just_post'), 
//			$price = 100, $privatekey = null, $url = null, $lat = null, $lon = null,
//			$tag = array('tag1', 'tag2')
//		);

//		$a2c->getSpecificListing('4fc33c047f8a7ee3400010b3');
			
//		fdump($a2c->result);
//		
//		die();
		
				
		$session = new Zend_Session_Namespace('add-ad-ad-local');
        $this->_helper->_layout->setLayout('add-an-ad-local-layout');
        if ($this->_request->isGet() || !$session->new_add){
			$ad = new Model_Listing_Preview();
			$ad->status = Model_Listing::STATUS_STARTED;
            $ad->save();
	        $session->listing_started = (string) $ad->_id;
	        $session->new_add = true;
        }
        
		$classname = 'Model_Listing_AddAnAdLocal';
		$u = Model_Listing_Preview::getInstance($classname, $session->listing_started);
		if (empty($u)) {
			$u = Model_Listing::getInstance($classname, $session->listing_started);
		}
		
        $options['adid'] = (string) $u->_id;
        $options['listing'] = $u;
        $form = $u->postAnAddForm($options);

        if ($this->_request->isPost() && !isset($_POST['postimg'])) {
        	if($form->isValid($_POST)){
				if(!empty($this->loggedin_user)){
					$_SERVER['HTTP_ADID'] = $u;
					$adA2c = $form->saveA2C();
					if(!isset($adA2c->error)){
		                $_POST = array();
		                $session->unsetAll();
		                $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
		                $to_be_confirmed_ads->unsetAll();
		                $session->infos[] = '分享成功';
		                $session->new_add = false;
		                $this->_redirect($this->view->geturl('addanadlocal', 'listing', null, 'default'));
					}else{
						$session->infos[] = $adA2c->error;
					}
	        	}else{
	        		$session->infos[] = '登陆后才能发布';
	        	}
        	}
        }

        if(isset($session->infos)){
        	$this->view->infos = $session->infos;
        	unset($session->infos);
        }
        $this->view->form = $form;
        $this->view->url_en = $this->url_en();
        $this->view->url_tc = $this->url_tc();
        $this->render('add-an-ad-local');
    }
    
    public function upimglocalAction()
    {
    	$session = new Zend_Session_Namespace('add-ad-ad-local');
        $this->_helper->_layout->setLayout('add-an-ad-local-layout');
        if ($this->_request->isGet() || !$session->new_add){
			$ad = new Model_Listing_Preview();
			$ad->status = Model_Listing::STATUS_STARTED;
            $ad->save();
	        $session->listing_started = (string) $ad->_id;
	        $session->new_add = true;
        }   

    	$classname = 'Model_Listing_AddAnAdLocal';
		$u = Model_Listing_Preview::getInstance($classname, $session->listing_started);
		if (empty($u)) {
			$u = Model_Listing::getInstance($classname, $session->listing_started);
		}
		
		if ($this->_request->isPost() && !empty($_FILES)) {
        	if(count($u->ph) <= 0){
	            if ($_FILES['upload1']['error'] != 4) {
	                $_SERVER['HTTP_ADID'] = $u;
	                $_SERVER['NOT_JSON'] = 1;
	                $res = Ac_Util::uploadListingPhotoProcess();
			
	                $options['img'] = $u->ph;
	            }
        	}
        }
        
		$options['adid'] = (string) $u->_id;
        $options['listing'] = $u;
        $u->postAnAddForm($options);
        
        $this->view->listing = $u;
        $this->view->adid = $session->listing_started;
        $this->render('photo-uploader-local');
    }
    
    
    public function grabcontentAction()
    {
    	if($this->_request->isGet()){
    		$grabContent = array();
    		$url = $this->_request->getParam('url', '');
    	    if(strpos($url, 'https://') !== 0){
	    		$url = 'http://' . str_replace('http://', '', $url);
	    	}
    		
    		$taobao = new Model_Taobao();
    		$taobao->setFields("detail_url,title,pic_url,price,item_img");
    		$taobao->getItemByUrl($url);
			if(isset($taobao->resp->item)){
				$grabContent['tb'] = $taobao->resp->item;
			}else{
    			$urlParse = Model_Util::parseUrl($url);
    			$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				if($urlParse['scheme'] == 'https'){
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				}
				curl_setopt($ch, CURLOPT_POST, 0);
				$content = curl_exec($ch);
				
				curl_close($ch);
	    		$matches = Model_Util::htmlRegCollection(array('img', 'title', 'h1'), $content, true);
	    		$grabContent['otherSite'] = $matches;
	    		$grabContent['otherSite']['url'] = $url;
			}
			$this->_helper->json($grabContent);
    	}
    }
    
    
}

